package main

import (
	amqp "github.com/rabbitmq/amqp091-go"
	"log"
)

func main() {
	// 连接 MQ
	conn, err := amqp.Dial("amqp://guest@localhost:5672/")
	failOnError("Failed to connect to RabbitMQ", err)
	defer conn.Close()

	// 创建一个通道操作 MQ
	ch, err := conn.Channel()
	failOnError("Failed to open a channel", err)
	defer ch.Close()

	// 声明一个队列，先确保队列存在，再从队列中消费消息
	q, err := ch.QueueDeclare(
		"hello",
		false,
		false,
		false,
		false,
		nil,
	)
	failOnError("Failed to declare a queue", err)

	// 消费队列
	msgs, err := ch.Consume(
		q.Name,
		"",
		true,
		false,
		false,
		false,
		nil,
	)
	failOnError("Failed to register a consumer", err)

	// MQ 服务器会异步的推送消息 要在一个 goroutine 中读取队列
	go func() {
		for d := range msgs {
			log.Printf("Received a message: %s", d.Body)
		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	select {}
}
func failOnError(msg string, err error) {
	if err != nil {
		log.Panicf("%s: %s", msg, err)
	}
}
